import time
from util.db_util import DBUtil
import logging

def wait_for_calculation_processing(file_id, process_type, timeout=600, interval=1):
    """
    等待文件处理完成
    
    Args:
        file_id: 文件ID
        timeout: 超时时间（秒）
        interval: 查询间隔（秒）
        
    Returns:
        str: 最终状态
    """
    start_time = time.time()
    
    while True:
        try:
            # 使用 DBUtil 查询状态
            sql = "SELECT PROCESS_ID, STATUS FROM [PPA].[TB_PPA_PROCESS_AUDIT] WHERE WF_ID = ? AND PROCESS = ?"
            row = DBUtil.select_one(sql, (file_id, process_type))
            
            if row:
                process_id = row[0]
                status = row[1]
                logging.info(f"[STATUS] wf_id={file_id} process_type={process_type} status: {status}")
                if status not in ("Pending", "Processing"):
                    return process_id, status
            else:
                logging.info(f"[INFO] No record found for wf_id={file_id}, process_type={process_type}, waiting...")
            
            if time.time() - start_time > timeout:
                logging.warning(f"[WARN] Timeout waiting for wf_id={file_id}, process_type={process_type} after {timeout}s")
                return None
            
            time.sleep(interval)
            
        except Exception as e:
            logging.error(f"[ERROR] Database query failed: {e}")
            time.sleep(interval)